package tr.seven;

import java.sql.*;
import java.util.Scanner;
public class Seven {
        // 数据库配置（按需修改）
        private static final String URL = "jdbc:mysql://localhost:3306/wangcai080";
        private static final String USER = "root";
        private static final String PASSWORD = "123456";

        public static void main(String[] args) {
            Scanner scanner = new Scanner(System.in);

            // 1. 获取员工信息
            System.out.println("----- 员工信息录入 -----");
            System.out.print("员工编号: ");
            int id = scanner.nextInt();

            System.out.print("姓名: ");
            String name = scanner.next();

            System.out.print("密码: ");
            String pwd = scanner.next();

            System.out.print("年龄: ");
            int age = scanner.nextInt();

            // 2. 创建员工对象
            Employee emp = new Employee(id, name, pwd, age);

            // 3. 数据库操作
            try {
                // 加载驱动
                Class.forName("com.mysql.cj.jdbc.Driver");

                // 建立连接
                try (Connection conn = DriverManager.getConnection(URL, USER, PASSWORD)) {

                    // 准备SQL (使用预处理防止SQL注入)
                    String sql = "INSERT INTO employee(id, name, password, age) VALUES (?, ?, ?, ?)";

                    // 创建预处理语句
                    try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
                        pstmt.setInt(1, emp.getId());
                        pstmt.setString(2, emp.getName());
                        pstmt.setString(3, emp.getPassword());
                        pstmt.setInt(4, emp.getAge());

                        // 执行插入
                        int rows = pstmt.executeUpdate();

                        // 结果反馈
                        if (rows > 0) {
                            System.out.println("\n✅ 员工信息保存成功!");
                        } else {
                            System.out.println("\n❌ 保存失败，请重试");
                        }
                    }
                }
            } catch (ClassNotFoundException e) {
                System.err.println("⚠️ 数据库驱动未找到: " + e.getMessage());
            } catch (SQLException e) {
                System.err.println("⚠️ 数据库错误: " + e.getMessage());
            } finally {
                scanner.close();
            }
        }
    }

